{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "collapsed": true,
    "ExecuteTime": {
     "end_time": "2023-07-13T17:04:43.559258Z",
     "start_time": "2023-07-13T16:56:13.984014Z"
    }
   },
   "outputs": [],
   "source": [
    "import os\n",
    "import pandas as pd\n",
    "from sklearn.model_selection import train_test_split, GridSearchCV, cross_val_score\n",
    "from sklearn.preprocessing import MinMaxScaler\n",
    "from sklearn.pipeline import Pipeline\n",
    "from sklearn.linear_model import LinearRegression\n",
    "from sklearn.tree import DecisionTreeRegressor\n",
    "from sklearn.svm import SVR\n",
    "from sklearn.neighbors import KNeighborsRegressor\n",
    "from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score, explained_variance_score, max_error, median_absolute_error\n",
    "\n",
    "# 加载数据集\n",
    "def load_data():\n",
    "    df = pd.read_csv('merged.csv')\n",
    "    df = df.dropna()\n",
    "    X = df.drop(columns=['openrank'])\n",
    "    y = df['openrank']\n",
    "    return X, y\n",
    "\n",
    "# 数据预处理\n",
    "def preprocess_data(X):\n",
    "    scaler = MinMaxScaler()\n",
    "    X_scaled = scaler.fit_transform(X)\n",
    "    return X_scaled\n",
    "\n",
    "# 模型训练和评估\n",
    "def train_and_evaluate_model(model, params, X, y):\n",
    "    # 划分训练集和测试集\n",
    "    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
    "\n",
    "    # GridSearchCV\n",
    "    grid = GridSearchCV(model, params, cv=5)\n",
    "    grid.fit(X_train, y_train)\n",
    "\n",
    "    # 模型预测\n",
    "    y_pred = grid.predict(X_test)\n",
    "\n",
    "    # 计算评估指标\n",
    "    mse = mean_squared_error(y_test, y_pred)\n",
    "    rmse = mean_squared_error(y_test, y_pred, squared=False)\n",
    "    mae = mean_absolute_error(y_test, y_pred)\n",
    "    r2 = r2_score(y_test, y_pred)\n",
    "    evs = explained_variance_score(y_test, y_pred)\n",
    "    max_err = max_error(y_test, y_pred)\n",
    "    med_abs_err = median_absolute_error(y_test, y_pred)\n",
    "\n",
    "    # 保存评估指标到CSV文件\n",
    "    result = pd.DataFrame({'Metric': ['MSE', 'RMSE', 'MAE', 'R-squared', 'Explained Variance', 'Max Error', 'Median Absolute Error'],\n",
    "                           'Value': [mse, rmse, mae, r2, evs, max_err, med_abs_err]})\n",
    "    return result\n",
    "\n",
    "# 主函数\n",
    "def main():\n",
    "    # 创建结果文件夹\n",
    "    if not os.path.exists('./result'):\n",
    "        os.makedirs('./result')\n",
    "\n",
    "    # 加载数据\n",
    "    X, y = load_data()\n",
    "\n",
    "    # 数据预处理\n",
    "    X_scaled = preprocess_data(X)\n",
    "\n",
    "    # 设置多个模型及其超参数\n",
    "    models = [\n",
    "        ('Linear Regression', LinearRegression(), {}),\n",
    "        ('Decision Tree', DecisionTreeRegressor(), {'max_depth': range(1,10)}),\n",
    "        ('Support Vector Machine', SVR(), {'kernel':['linear', 'poly', 'rbf', 'sigmoid'], 'C':[1, 10]}),\n",
    "        ('K-Nearest Neighbors', KNeighborsRegressor(), {'n_neighbors': range(1,10)})\n",
    "    ]\n",
    "\n",
    "    results = []  # 存储结果的列表\n",
    "\n",
    "    for name, model, params in models:\n",
    "        # 模型训练和评估\n",
    "        result = train_and_evaluate_model(model, params, X_scaled, y)\n",
    "\n",
    "        # 添加结果到列表\n",
    "        result['Model'] = name\n",
    "        results.append(result)\n",
    "\n",
    "    # 合并结果为一个DataFrame\n",
    "    result_df = pd.concat(results)\n",
    "\n",
    "    # 保存结果为CSV文件\n",
    "    result_path = \"./result/all_results.csv\"\n",
    "    result_df.to_csv(result_path, index=False)\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
